<template>
	<el-dialog v-if="visible" :title="dataForm.layerManagerId ? '编辑图层' : '创建图层'" v-model="visible" :close-on-click-modal="false" draggable>
		<div class="flex">
			<el-form :model="dataForm" v-loading="loading" style="width: 45%">
				<el-form-item label="资源选择" prop="type">
					<div class="flex w-full">
						<p
							class="justify-center items-center tabList cursor-pointer gap-2"
							v-for="(item, index) in tabList"
							:key="item.text"
							@click="tabHandle(item, index)"
							:class="active == index ? 'actived' : ''"
						>
							<!-- <i class="iconfont" :class="item.icon"></i> -->
							<span>{{ item.text }}</span>
						</p>
					</div>
				</el-form-item>
				<el-form-item>
					<el-input placeholder="请输入数据源名称查询" style="max-width: 65%" v-model="state.queryForm.fileNameCh" clearable />
					<el-select
						v-model="state.queryForm.dataType"
						placeholder="请选择格式"
						style="max-width: 30%"
						class="ml10"
						:suffix-icon="IconDropDown"
						clearable
					>
						<el-option v-for="item in dataType" :key="item.value" :label="item.text" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-table
					class="table-left"
					:data="state.dataList"
					:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
					row-key="path"
					style="width: 100%"
					:cell-style="tableStyle.cellStyle"
					:header-cell-style="tableStyle?.headerCellStyle"
					@filter-change="filterChange"
				>
					<el-table-column prop="fileNameCh" label="资源名称" show-overflow-tooltip />
					<el-table-column prop="dataSourceType" label="类型" :filters="dataSourceType" column-key="dataSourceType" :filter-multiple="false">
						<template #default="scope">
							<el-tag class="h-8" size="large">{{ filterDataType(scope.row.dataSourceType, 'name', 'dataSourceType') }} </el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="dataType" label="格式" :filters="dataType" column-key="dataType" :filter-multiple="false">
						<template #default="scope">
							<el-tag class="h-8" size="large">{{ filterDataType(scope.row.dataType, 'name', 'dataType') }} </el-tag>
						</template>
					</el-table-column>
					<el-table-column
						prop="publishStatus"
						label="发布状态"
						:filters="[
							{ text: '已发布', value: 1 },
							{ text: '未发布', value: 0 },
						]"
						column-key="publishStatus"
						:filter-multiple="false"
					>
						<template #default="scope">
							<el-tag :color="scope.row.publishStatus == 1 ? '#DAF7C9' : '#E8EAF1'">{{ scope.row.publishStatus == 1 ? '已发布' : '未发布' }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="checked" label="选择" width="55">
						<template #default="scope">
							<el-checkbox v-model="scope.row.checked" @change="() => handleCheck(scope.row)"></el-checkbox>
						</template>
					</el-table-column>
				</el-table>
				<pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle"> </pagination>
			</el-form>

			<el-form ref="layerDialogFormRef" label-position="left" :model="dataForm" v-loading="loading" class="ml20" style="width: 54%">
				<el-form-item prop="layerNameCh" label="图层名称" class="mt10" required>
					<el-input placeholder="请输入图层名称" clearable v-model.trim="dataForm.layerNameCh" />
				</el-form-item>
				<el-form-item prop="projectName" label="图层分组" required>
					<el-select v-model="dataForm.projectName" :suffix-icon="IconDropDown" placeholder="选择所属项目" @change="handleProject()" clearable>
						<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="图层说明" prop="layerRemarks">
					<el-input v-model="dataForm.layerRemarks" type="textarea" clearable placeholder="请输入图层说明"></el-input>
				</el-form-item>
				<el-form-item label="服务路径" prop="sourceServiceUrl" v-if="checkedFile.dataType == 6">
					<el-input v-model="checkedFile.sourceServiceUrl" type="textarea" clearable placeholder="请输入图层说明" disabled></el-input>
				</el-form-item>
				<div class="mt10" v-if="checkedFile.dataType == 6">
					<el-form-item label="初始范围">
						<el-row :gutter="20" class="mt10">
							<el-col :span="5">
								<el-input v-model="dataForm.boxMinX" placeholder="最小X"></el-input>
								<el-text class="mr10 ml20">西经</el-text>
							</el-col>
							<el-col :span="5">
								<el-input v-model="dataForm.boxMinY" placeholder="最小Y"></el-input>
								<el-text class="mr10 ml20">南纬</el-text>
							</el-col>
							<el-col :span="5">
								<el-input v-model="dataForm.boxMaxX" placeholder="最大X"></el-input>
								<el-text class="mr10 ml20">东经</el-text>
							</el-col>
							<el-col :span="5">
								<el-input v-model="dataForm.boxMaxY" placeholder="最大Y"></el-input>
								<el-text class="mr10 ml20">北纬</el-text>
							</el-col>
						</el-row>
					</el-form-item>
				</div>
				<el-form-item  v-if="checkedFile.dataType == 4">
					<el-input placeholder="请输入图层名称查询" v-model="filterLayerName" clearable @input='getTableList' />
				
				</el-form-item>
				<div class="table-container table-left mb10" style="max-height: 522px" v-if="checkedFile.dataType == 4">
					<el-table
						:data="dataTableList"
						@filter-change="filterChange"
						style="width: 100%"
						height="522"
						:header-cell-style="{ position: 'sticky', top: 0, zIndex: 1 }"
					>
						<el-table-column prop="tableName" label="图层名称" show-overflow-tooltip />
						<el-table-column
							prop="publishStatus"
							label="发布状态"
							:filters="[
								{ text: '已发布', value: 1 },
								{ text: '未发布', value: 0 },
							]"
							column-key="publishStatus"
							:filter-multiple="false"
						>
							<template #default="scope">
								<el-tag :color="scope.row.publishStatus == 1 ? '#DAF7C9' : '#E8EAF1'">
									{{ scope.row.publishStatus == 1 ? '已发布' : '未发布' }}
								</el-tag>
							</template>
						</el-table-column>

						<el-table-column prop="checked" label="选择" width="55">
							<template #default="scope">
								<el-checkbox v-model="scope.row.checked" @change="() => handleSelectionChange(scope.row)" />
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div
					class="blue-card mt20"
					v-if="checkedFile.dataType == 4 || ((checkedFile.dataType == 1 || checkedFile.dataType == 2) && checkedFile.fileId)"
				>
					<el-form-item prop="fileNameCh" label="坐标系统" class="ml10">
						<el-select
							v-model="dataForm.srs"
							filterable
							remote-show-suffix
							remote
							:loading="selectLoading"
							:suffix-icon="IconDropDown"
							:remote-method="remoteMethod"
							placeholder="请选择坐标系"
							:disabled="!checkedTable"
						>
							<el-option v-for="item in srsOptions" :key="item.id" :label="item.name" :value="item.name" />
						</el-select>
					</el-form-item>
					<p></p>
					<div class="mt10">
						<el-text class="mr10 ml20">包围盒边框</el-text>
						<el-row :gutter="20" class="mt10 ml20">
							<el-col :span="6">
								<el-input v-model="dataForm.boxMinX" placeholder="最小X" disabled></el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.boxMinY" placeholder="最小Y" disabled></el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.boxMaxX" placeholder="最大X" disabled></el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.boxMaxY" placeholder="最大Y" disabled></el-input>
							</el-col>
						</el-row>
					</div>

					<div class="mt10">
						<el-text class="mr10 ml20">经纬度边框</el-text>
						<el-row :gutter="20" class="mt10 ml20">
							<el-col :span="6">
								<el-input v-model="dataForm.latLonBoxMinX" placeholder="最小X" disabled> </el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.latLonBoxMinY" placeholder="最小Y" disabled></el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.latLonBoxMaxX" placeholder="最大X" disabled></el-input>
							</el-col>
							<el-col :span="6">
								<el-input v-model="dataForm.latLonBoxMaxY" placeholder="最大Y" disabled></el-input>
							</el-col>
						</el-row>
					</div>
					<div class="text-center">
						<el-button class="sum-btn" type="primary" @click="borderCalculation">计算</el-button>
					</div>
				</div>
				<el-row :gutter="20" v-if="checkedFile.dataSourceType == 2">
					<el-col :span="12">
						<el-form-item label="矢量类型" prop="styleType">
							<el-select v-model="dataForm.styleType" :suffix-icon="IconDropDown" placeholder="选择类型" @change="handleProject()" clearable>
								<el-option v-for="item in styleType" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="图层样式" prop="dataSourceType">
							<el-select v-model="dataForm.styleName" :suffix-icon="IconDropDown" placeholder="选择样式" clearable>
								<el-option v-for="item in styleOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="close()" :disabled="loading">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="layerDialog">
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import {} from '/@/api/project';
import {
	pageList,
	getTableDataSourceInfo,
	addGeoLayer,
	getInfoById,
	updateGeoLayer,
	getBorderCalculation,
	getGeoBoxLatLonData,
	getAllWorkSpaceList,
} from '/@/api/resource/layerManagement';
import { getCoordinatelist } from '/@/api/project';
import { getOptName } from '/@/utils/arrayOperation';
import DropDown from '/@/assets/icons/drop-down.svg';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { getFileList, delFileList, downFile, saveSubmit, updateDataLabel, fileDataSourceObj, getStyle } from '/@/api/project/index';
import { useDict } from '/@/hooks/dict';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();

const { styleType } = useDict('styleType');

const projectOptions = ref([]);

// 定义变量内容
const isInit = ref(false);
const visible = ref(false);
const loading = ref(false);
const selectLoading = ref(false);
const layerDialogFormRef = ref();
const srsOptions = ref<any[]>([]);
const active = ref('0');
let currentCheckedId = null; // 存储当前勾选的项的ID
let checkedFile = ref({}); // 存储当前勾选的项的文件
let checkedTable = ref({}); // 存储当前数据
let checkedTableId = null; // 存储当前数据的ID
const dataTableList = ref([]);
const tabList = ref([
	{
		text: '全部',
		icon: 'icon-a-3d1',
	},
	{
		text: '二维矢量',
		icon: 'icon-a-3d1',
		num: 2,
	},
	{
		text: '三维数据',
		icon: 'icon-a-3d1',
		num: 3,
	},
	{
		text: '底图服务',
		icon: 'icon-a-3d1',
		num: 1,
	},
]);

const dataSourceType = ref<any[]>([
	{ text: '基础底图', value: '1' },
	{ text: '二维矢量', value: '2' },
	{ text: '三维模型', value: '3' },
]);

const dataType = ref<any[]>([
	{ text: 'Shapefile', value: '1' },
	{ text: 'Tif', value: '2' },
	{ text: '3Dtiles', value: '3' },
	{ text: 'PostGIS', value: '4' },
	{ text: 'Fbx/Glb', value: '5' },
	{ text: '瓦片地图', value: '6' },
	{ text: '地形', value: '7' },
	{ text: 'WMS服务', value: '8' },
]);
const fileOptions = ref<any[]>([]);
const styleOptions = ref<any[]>([]);
const coorForm = ref({
	size: 100,
	current: 1,
	name: '',
});
let filterLayerName = ref('')
// 定义需要的数据
let dataForm = reactive({
	layerManagerId: '',
	wokeSpaceName: '',
	layerName: '',
	layerNameCh: '',
	projectName: '',
	layerRemarks: '',
	srs: '',
	latLonBoxMinX: '',
	latLonBoxMinY: '',
	latLonBoxMaxX: '',
	latLonBoxMaxY: '',
	boxMaxX: '',
	boxMaxY: '',
	boxMinX: '',
	boxMinY: '',
	styleName: '',
	styleType: null,
});

const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

const state: BasicTableProps = reactive<BasicTableProps>({
	pageList: getFileList,
	queryForm: {},
});
const { getDataList, tableStyle, currentChangeHandle, sizeChangeHandle } = useTable(state);

const getQuery = watch(
	[() => state.queryForm.fileNameCh, () => state.queryForm.dataType, () => state.queryForm.dataSourceType],
	(newValues, oldValues) => {
		getDataList();
	}
);

// 过滤筛选列表
const filterChange = (filter) => {
	if (filter['dataType']) {
		state.queryForm.dataType = filter.dataType.join(',');
		getDataList();
	} else if (filter['dataSourceType']) {
		state.queryForm.dataSourceType = filter.dataSourceType.join(',');
		getDataList();
	} else if (filter['publishStatus']) {
		state.queryForm.publishStatus = filter.publishStatus.join(',');
		getDataList();
	} else {
		state.publishStatus = filter.publishStatus.join(',');
		getTableList();
	}
};

const getTableList = async (id) => {
  const params = {
    dataSourceId: state.dataSourceId,
  };
  if (filterLayerName.value) {
    params.tableName = filterLayerName.value;
  }

  await getTableDataSourceInfo(params).then((res) => {
    dataTableList.value = res.data;
  });
};
//数据源类型切换
const tabHandle = (item, index) => {
	state.queryForm.dataSourceType = item.num ? item.num : '';
	active.value = index;
	getDataList();
};

const handleCheck = (row) => {
	checkedFile.value = row;
	if (currentCheckedId === row.fileDataSourceId) {
		// 如果当前勾选的已经是这个项，则取消勾选
		currentCheckedId = null;
		checkedFile.value = {};
	} else {
		// 否则，更新当前勾选的项
		currentCheckedId = row.fileDataSourceId;
	}

	state.dataList.forEach((item) => {
		item.checked = item.fileDataSourceId === currentCheckedId;
	});
	// 获取当前勾选项
	getCurrentCheckedItem();
	if (row.dataType == 4) {
		state.dataSourceId = row.dataSourceId;
		getTableList();
	}
};

const getCurrentCheckedItem = () => {
	if (currentCheckedId !== null) {
		state.dataList.find((item) => {
			item.fileDataSourceId === currentCheckedId;
		});
	} else {
		checkedFile.value = {};
		// console.log('没有勾选项');
	}
};

// 选择数据
const handleSelectionChange = (row) => {
	checkedTable.value = row;
	if (checkedTableId === row.tableName) {
		checkedTableId = null;
		checkedTable.value = {};
	} else {
		checkedTableId = row.tableName;
	}

	dataTableList.value.forEach((item) => {
		item.checked = item.tableName === checkedTableId;
	});

	// 获取当前勾选项
	getTableCheckedItem();
	if (row.dataType == 4) {
		state.dataSourceId = row.dataSourceId;
		getTableList();
	}
};
const getTableCheckedItem = () => {
	if (checkedTableId !== null) {
		const currentItem = dataTableList.value.find((item) => item.tableName === checkedTableId);
	} else {
		checkedTable.value = {};
		// console.log('没有勾选项');
	}
};

// 获取坐标系方法
function remoteMethod(val) {
	selectLoading.value = true;
	coorForm.value.name = val;
	getCoordinatelist(coorForm.value).then((res) => {
		let { data } = res;
		srsOptions.value = data.records;
		selectLoading.value = false;
	});
}

// 获取样式
async function handleProject() {
	let query = {
		styleType: dataForm.styleType,
		projectName: dataForm.projectName,
	};
	const { data } = await getStyle(query);
	styleOptions.value = data.map((item: any) => {
		return {
			label: item.styleNameCh,
			value: item.styleName,
		};
	});
}

// 边框计算
const borderCalculation = async () => {
	if (!dataForm.srs) {
		useMessage().error('请选择坐标系统！');
		return;
	}
	try {
		loading.value = true;
		const { data } = await getBorderCalculation({
			columnName: checkedTable.value.columnName,
			tableName: checkedTable.value.tableName,
			wokeSpaceName: checkedFile.value.wokeSpaceName,
			storeName: checkedFile.value.fileDataName,
			srs: dataForm.srs,
		});
		dataForm.latLonBoxMinX = data.boxMinx;
		dataForm.latLonBoxMinY = data.boxMiny;
		dataForm.latLonBoxMaxX = data.boxMaxx;
		dataForm.latLonBoxMaxY = data.boxMaxy;
		LatLonCalculation();
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 经纬度计算
const LatLonCalculation = async () => {
	try {
		loading.value = true;
		const { data } = await getGeoBoxLatLonData({
			srs: dataForm.srs,
			boxMinx: dataForm.boxMinX,
			boxMiny: dataForm.boxMinY,
			boxMaxx: dataForm.boxMaxX,
			boxMaxy: dataForm.boxMaxY,
		});

		dataForm.boxMinX = data.boxMinx;
		dataForm.boxMinY = data.boxMiny;
		dataForm.boxMaxX = data.boxMaxx;
		dataForm.boxMaxY = data.boxMaxy;
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

//判断类型
const filterType = (type: string, key: any) => {
	const typeName = dataSourceType.value.find((item) => {
		return item.id == type;
	});
	if (typeName) {
		return typeName[key];
	} else {
		return undefined;
	}
};
//判断格式
const filterDataType = (type: string, key: any, name: any) => {
	if (name == 'dataType') {
		const formatName = dataType.value.find((item) => item.value == type);
		return formatName ? formatName.text : '';
	} else if (name == 'dataSourceType') {
		const typeName = dataSourceType.value.find((item) => item.value == type);
		return typeName ? typeName.text : '';
	}
};
// 根据项目获取文件列表
const getFileOptionsByProject = async (projectName: any) => {
	if (!isInit.value) dataForm.storeName = '';
	const { data } = await fileDataSourceObj({ projectName: projectName, serviceType: dataForm.serviceType });
	fileOptions.value = data.map((item: any) => {
		return {
			label: `${item.fileNameCh}(${getOptName(dataType.value, item.dataType)})`,
			dataType: item.dataType,
			value: item.fileDataName,
		};
	});
};

// 打开弹窗
const openDialog = (type: string, form?: any) => {
	close();
	visible.value = true;
	if (form) {
		dataForm.projectName = form.dataType;
	}

	// 获取坐标系统
	remoteMethod();
	nextTick(async () => {
		layerDialogFormRef.value?.resetFields();
		active.value = 0;
		getDataList();
		checkedFile.value = {};
		checkedTable.value = {};
		//  初始文件列表都不选中
		state.dataList.forEach((item) => {
			item.checked = false;
		});
		getAllWorkSpaceList({}).then((res) => {
			let { data } = res;
			projectOptions.value = data.map((item) => {
				return {
					label: item.projectNameCh,
					value: item.wokeSpaceName,
				};
			});
		});
	});
};

// 初始化表单数据
const getLayerInfo = (id: string) => {
	isInit.value = true;
	// 获取数据
	getInfoById(id)
		.then((res: any) => {
			Object.assign(dataForm, res.data);
			getFileOptionsByProject(dataForm.wokeSpaceName);
		})
		.finally(() => {
			isInit.value = false;
		});
};

const close = () => {
	visible.value = false;
	dataForm.layerManagerId = '';
	dataForm.wokeSpaceName = '';
	dataForm.layerName = '';
	dataForm.layerNameCh = '';
	dataForm.projectName = '';
	dataForm.layerRemarks = '';
	dataForm.srs = '';
	dataForm.latLonBoxMinX = '';
	dataForm.latLonBoxMinY = '';
	dataForm.latLonBoxMaxX = '';
	dataForm.latLonBoxMaxY = '';
	dataForm.boxMaxX = '';
	dataForm.boxMaxY = '';
	dataForm.boxMinX = '';
	dataForm.boxMinY = '';
	dataForm.styleName = '';
	dataForm.styleType = null;
	state.queryForm.dataType = '';
	state.queryForm.fileNameCh = '';
	filterLayerName.value=''
};
// 保存数据
const onSubmit = async () => {
	Object.assign(dataForm, checkedFile.value);
	dataForm.publishStatus = 1; //启用状态
	// shp根据上传类型判断
	if (dataForm.fileId && dataForm.dataSourceType == 2) {
		dataForm.serviceType = 1;
	} else {
		dataForm.serviceType = 2;
	}
	// 数据源  文件上传给fileDataName  本地路径给sourceServiceUrl
	dataForm.storeName = checkedFile.value.fileDataName ? checkedFile.value.fileDataName : checkedFile.value.sourceServiceUrl;
	dataForm.layerName = '';
	const valid = await layerDialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	if (dataForm.dataType == 4) {
		dataForm.serviceType = 1;
		dataForm.storeName = dataForm.fileDataName;
		dataForm.layerName = checkedTable.value.tableName;
		dataForm.dataSourceId = state.dataSourceId;
	}
	// 删除多余参数
	const propertiesToDelete = [
		'styleType',
		'fileId',
		'fileDataName',
		'projectNameCh',
		'fileRemarks',
		'fileNameCh',
		'dataSourceName',
		'sourceServiceUrl',
		'createTime',
		'updateTime',
		'host',
		'port',
		'password',
		'username',
		'databaseName',
		'checked',
		'uploadStatus',
		'fileUid',
	];

	for (const prop of propertiesToDelete) {
		delete dataForm[prop];
	}
	try {
		loading.value = true;
		let res = dataForm.layerManagerId ? await updateGeoLayer(dataForm) : await addGeoLayer(dataForm);
		if (res.code == 0) {
			useMessage().success(t(dataForm.layerManagerId ? 'common.editSuccessText' : 'common.publishSuccessText'));
			visible.value = false;
			emit('refresh');
		}
	} catch (err: any) {
		// useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
	display: block;
}
:deep(.el-radio-button__inner) {
	color: #3156a5;
	background-color: #edf0f7;
	width: 164px !important;
}
.dialog-footer {
	display: flex;
	justify-content: flex-end;
}

.blue-card {
	margin: 5px 5px 20px 5px;
	padding: 10px;
	background: #edf0f7;
	padding-left: 0px;
}
.flex {
	display: flex;
	justify-content: space-between;
}
.text-center {
	text-align: right;
	margin-top: 18px;
}
.sum-btn {
	width: 180px;
}
.table-left {
	border: 1px solid #3156a5;
}
.tabList {
	background: #eaf1ff;
	border-radius: 2px;
	color: #3156a5;
	width: 24%;
	padding: 0px 6px;
	display: flex;
}
.actived {
	background: #3156a5;
	color: #fff;
}
.mb10 {
	margin-bottom: 10px;
}
.table-container {
	max-height: 320px;
	overflow-y: auto;
	overflow: visible;
}
::v-deep(.el-pagination) {
  margin-top: 0;
    justify-content: flex-start !important;
	flex-wrap: wrap;
}
</style>
